package jm.easyconfig.standalone;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

//import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
//import org.springframework.amqp.rabbit.connection.ConnectionFactory;
//import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.rabbitmq.client.Channel;

import jm.easyconfig.CfgContextEnvironmentAware;
import jm.easyconfig.EasyValue;

@RestController
public class CfgController {

//	@Autowired
//	CachingConnectionFactory factory;
////	{
////		factory.createConnection()
////	}
//
//	@Autowired
//	RabbitTemplate rabbitTempate;
//
//	@PostConstruct
//	public void init() {
//		Channel chn = rabbitTempate.getConnectionFactory().createConnection().createChannel(false);
//		System.out.println(chn);
//	}

	@EasyValue(value = "${test.port:8090}", name = "hihihi")
	public int port;

	@Autowired
	private HttpSession session;

	@Autowired
	ApplicationContext applicationContext;

	@Autowired
	ConfigurableEnvironment environment;

	@Autowired
	CfgService cfgService;

	@GetMapping("/hello")
	public Object hello() {
		return "world";
	}

	@GetMapping("/service")
	public String service() throws Throwable {
		return cfgService.toString();
	}

	@GetMapping("/login")
	public Object test(String user) throws Throwable {
		session.setAttribute("user", new Object() {
			public String name = user;
			public String email = user + "@jm.com.cn";

			@Override
			public String toString() {

				return email;
			}

		});

		return session.getAttribute("user");
	}

	@GetMapping("/user")
	public Object session() {
		HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return req.getSession().getAttribute("easyconfig-security-user");
	}

	@GetMapping("/props")
	public Object props() {
		return environment.getPropertySources().get("easyconfig_dynamic_property_source").getSource();
	}

	@Autowired
	CfgContextEnvironmentAware aware;

	@GetMapping("/inspect")
	public Object inspect(String prop) {

		return aware.inspect(prop);

	}
}
